package cn.baage.campus.config;

import cn.baage.campus.enums.ExceptionType;
import cn.baage.campus.exception.BizException;
import cn.baage.campus.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.Optional;

/**
 * @Description: 全局异常处理
 * @Author: 八阿哥
 * @url: baage.cn
 * @Version: 1.0
 **/
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {


    /**
     * 请求方式不支持
     */
    @ExceptionHandler({ HttpRequestMethodNotSupportedException.class })
    public Result<Object> handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e,
                                                              HttpServletRequest request) {
        log.info("请求地址({})不支持'{}'请求", request.getRequestURI(), e.getMethod());
        return Result.fail(ExceptionType.REQUEST_METHODS_ERROR.getErrorCode() , ExceptionType.REQUEST_METHODS_ERROR.getErrorMessage());
    }


    /**
     * 捕获参数校验异常
     */
    @ExceptionHandler({ MethodArgumentNotValidException.class })
    public Result<Object> handleMethodArgumentNotValidException(MethodArgumentNotValidException e,
                                                                HttpServletRequest request) {
        Integer errorCode = ExceptionType.PARAM_NOT_VALID.getErrorCode();
        // 获取 BindingResult
        BindingResult bindingResult = e.getBindingResult();
        StringBuilder sb = new StringBuilder();
        Optional.of(bindingResult.getFieldErrors()).ifPresent(errors -> {
            // 获取校验失败字段，包含 字段名、传值 以及 拒绝消息等信息
            FieldError fieldError = errors.get(0);
            sb.append(fieldError.getField()).append("：").append(fieldError.getDefaultMessage());
        });
        // 错误信息
        String errorMessage = sb.toString();
        log.info("请求地址({}) 参数校验异常", request.getRequestURI());
        return Result.fail(errorCode, errorMessage);
    }


    /**
     * 捕获业务异常
     */
    @ExceptionHandler( {BizException.class} )
    public Result<Object> handleBizException(BizException bizException, HttpServletRequest request) {
        Integer errorCode = bizException.getErrorCode();
        String errorMessage = bizException.getErrorMessage();
        log.info("请求地址({})发生业务异常：errorCode: {}, errorMessage: {}", request.getRequestURI(), errorCode, errorMessage);
        return Result.fail(errorCode, errorMessage);
    }


}
